package data.connector.rippling.oauth;

import data.connector.rippling.api.base.BaseGenericService;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;

/**
 *
 * @author Alex bob(https://github.com/vnobo)
 * @date Created by 2020/3/19
 */
@Log4j2
@Service
@RequiredArgsConstructor
public class AuthService extends BaseGenericService {

    private final String REDIS_TOKEN_KEY_PREFIX = "oauth:";

    private final static String token="dENKQN2KuMNPgsQJIV1MCqTUnoq3zJf2SougAJTme7mykM31Ln4LQ6OfVwYN6amk";

    public Mono<String> getToken(Integer tenantId) {
       return this.reactiveRedisTemplate.opsForValue()
                .get(this.REDIS_KEY_PREFIX + this.REDIS_TOKEN_KEY_PREFIX + tenantId + ":access_token")
                .switchIfEmpty(this.getDbToken(tenantId))
                .onErrorResume(err -> Mono.just(err.getMessage()))
               .map(result -> this.objectMapper.convertValue(result, String.class));
    }

    private Mono<String> getDbToken(Integer tenantId) {
        //select dbData
        this.reactiveRedisTemplate.opsForValue()
                .set(this.REDIS_KEY_PREFIX + this.REDIS_TOKEN_KEY_PREFIX + tenantId + ":access_token",token).subscribe();
        return Mono.just(token);
    }
}
